//纸张对应尺寸 mm
export const paperTypes: any = { A4: [210, 297], A5: [148, 210], A6: [105, 148] };
//照片对应尺寸 mm
export const imgInchs: any = { Inch1: [25, 35], Inch2: [35, 45] };
//纸张边宽 mm
export const passportPageHorizontalPadding = 10; //水平
export const passportPageVerticalPadding = 8; // 垂直

//照片间距 mm
export const passportPadding = 4;

export const getPassportAttr = (paper: string, inch: string) => {
	paper = paper || 'A4';
	inch = inch || 'Inch1';
	const paperWidth = paperTypes[paper][0];
	const paperHeight = paperTypes[paper][1];
	const paperBoxWidth = paperWidth - passportPageHorizontalPadding * 2;
	const paperBoxHeight = paperHeight - passportPageVerticalPadding * 2;
	const passportWidth = imgInchs[inch][0];
	const passportHeight = imgInchs[inch][1];
	const passportBoxWidth = passportWidth + passportPadding * 2;
	const passportBoxHeight = passportHeight + passportPadding * 2;
	const horizontalPassportCount = Math.floor(paperBoxWidth / passportBoxWidth); //水平数量
	const verticalPassportCount = Math.floor(paperBoxHeight / passportBoxHeight);
	//得出水平照片数量、垂直照片数量、照片盒子宽度、照片盒子高度、照片宽度、照片高度、纸张宽度、纸张高度(毫米mm)
	return { horizontalPassportCount, verticalPassportCount, passportBoxWidth, passportBoxHeight, passportWidth, passportHeight, paperWidth, paperHeight };
};

export const getPassportMaxCount = (paper: string, inch: string) => {
	const { horizontalPassportCount, verticalPassportCount } = getPassportAttr(paper, inch);
	return horizontalPassportCount * verticalPassportCount;
};

export const createPassportPageBase64 = (passportImageData: any, paper: string, inch: string, total: number) => {
	const { horizontalPassportCount, verticalPassportCount, passportBoxWidth, passportBoxHeight, passportWidth, passportHeight, paperWidth, paperHeight } = getPassportAttr(paper, inch);
	//获取证件照片的像素宽高
	const { width: passportPixelWidth, height: passportPixelHeight } = passportImageData;
	//获取每毫米有多少像素
	const unitPixel = passportPixelWidth / passportWidth;
	//创建临时画板
	const tmpCanvas = document.createElement('canvas');
	tmpCanvas.width = paperWidth * unitPixel;
	tmpCanvas.height = paperHeight * unitPixel;
	const tmpCtx = tmpCanvas.getContext('2d');
	if (!tmpCtx) return;
	//填充画板为白色底色
	tmpCtx.fillStyle = 'white';
	tmpCtx.fillRect(0, 0, tmpCanvas.width, tmpCanvas.height);
	let startX = undefined;
	let startY = undefined;
	let printCount = 0;
	outerLoop: for (let v = 0; v < verticalPassportCount; v++) {
		//垂直方向循环
		startY = (passportPageVerticalPadding + passportBoxHeight * v + passportPadding) * unitPixel;
		for (let h = 0; h < horizontalPassportCount; h++) {
			startX = (passportPageHorizontalPadding + passportBoxWidth * h + passportPadding) * unitPixel;
			tmpCtx.drawImage(passportImageData, startX, startY, passportWidth * unitPixel, passportHeight * unitPixel);
			printCount++;
			//如果超出，停止
			if (printCount > total) {
				break outerLoop;
			}
		}
	}
	return tmpCanvas.toDataURL('image/png');
};
